package cn.com.czpb.client.module.live.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
//import android.webkit.DownloadListener;
//import android.webkit.WebSettings;
//import android.webkit.WebView;
//import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.tencent.smtt.sdk.DownloadListener;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.com.czpb.client.R;
import cn.com.czpb.client.api.InterfaceJsonfile;
import cn.com.czpb.client.app.MToolBarActivity;
import cn.com.czpb.client.model.live.LiveDetailEntity;
import cn.com.czpb.client.model.live.LiveItemBean;
import cn.com.czpb.client.model.news.ComResultEntity;
import cn.com.czpb.client.model.news.CommentBean;
import cn.com.czpb.client.model.news.IsCollectionEntity;
import cn.com.czpb.client.model.news.PraiseNumEntity;
import cn.com.czpb.client.module.dialog.ShareDialog;
import cn.com.czpb.client.module.news.dialog.ReplyDialog;
import cn.com.czpb.client.net.Factory;
import cn.com.czpb.client.utils.DeviceUtils;
import cn.com.czpb.client.utils.LogUtils;
import cn.com.czpb.client.utils.PageCtrl;
import cn.com.czpb.client.utils.ParamUtils;
import cn.com.czpb.client.utils.TUtils;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by 猪猪侠 on 2017/10/31.
 */

public class LiveDetailActivity extends MToolBarActivity {

    @BindView(R.id.webview_id)
    WebView webview;
    @BindView(R.id.img_back)
    LinearLayout imgBack;
    @BindView(R.id.img_comment)
    ImageView imgComment;
    @BindView(R.id.comment_number_tx)
    TextView commentNumberTx;
    @BindView(R.id.ll_newdetail_comments)
    LinearLayout llNewdetailComments;
    @BindView(R.id.img_praise)
    ImageView imgPraise;
    @BindView(R.id.praise_number_tx)
    TextView praiseNumberTx;
    @BindView(R.id.ll_newdetail_praise)
    LinearLayout llNewdetailPraise;
    @BindView(R.id.img_collection)
    ImageView imgCollection;
    @BindView(R.id.collection_number_tx)
    TextView collectionNumberTx;
    @BindView(R.id.ll_newdetail_collection)
    LinearLayout llNewdetailCollection;
    @BindView(R.id.img_share)
    ImageView imgShare;
    @BindView(R.id.share_number_tx)
    TextView shareNumberTx;
    @BindView(R.id.ll_newdetail_share)
    LinearLayout llNewdetailShare;
    @BindView(R.id.news_detail_ll_bottom1)
    LinearLayout newsDetailLlBottom1;
    private LiveItemBean bean;
    private LiveItemBean ndb;

    @Override
    protected int setLayoutId() {
        return R.layout.activity_livedetail;
    }

    @Override
    public void initView() {
        Intent intent = getIntent();
        bean = (LiveItemBean) intent.getSerializableExtra("bean");
        getLiveDetailData(bean.getId());
//        String url = "http://101.200.174.98/gxjhxt/api.php?s=/Live/live/id/2";
//        String url = bean.getNewsurl();
        //0000
        //添加下载文件监听
        webview.setDownloadListener(new OnDownloadListener());
        WebSettings webSetting = webview.getSettings();
        webSetting.setJavaScriptEnabled(true);
        webSetting.setJavaScriptCanOpenWindowsAutomatically(true);
        webSetting.setAllowFileAccess(true);
        webSetting.setUseWideViewPort(true);
        webSetting.setLoadWithOverviewMode(true);
        webSetting.setAppCacheEnabled(true);
        webSetting.setAppCachePath(getAllDiskCacheDir() + File.separator + "webView");
        webSetting.setDatabaseEnabled(true);
        webSetting.setDomStorageEnabled(true);
        webSetting.setSavePassword(false);
        webSetting.setCacheMode(WebSettings.LOAD_NO_CACHE);
//        //开启混合加载模式，允许https链接中加载http的内容
//        if (Build.VERSION.SDK_INT >= 21) {
//            webSetting.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
//        }

        //移除三个危险漏洞的接口
        if (Build.VERSION.SDK_INT < 17) {
            try {
                webview.removeJavascriptInterface("searchBoxJavaBridge_");
                webview.removeJavascriptInterface("accessibility");
                webview.removeJavascriptInterface("accessibilityTraversal");
            } catch (Throwable tr) {
                tr.printStackTrace();
            }
        }
        webview.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
//                view.loadUrl(url);
                return super.shouldOverrideUrlLoading(view, url);
            }
        });


    }



    @OnClick({R.id.img_back, R.id.ll_newdetail_comments, R.id.ll_newdetail_praise, R.id.ll_newdetail_collection, R.id.ll_newdetail_share})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_back:
                this.finish();
                break;
            case R.id.ll_newdetail_collection:

                if (spu.getUser() != null) {
                    addCollection();
                } else {
                    PageCtrl.start2LoginActivity(activity);
                }
                break;
            case R.id.ll_newdetail_share:
                if(spu.getUser() != null) {
                    String imgurl = null;
                    if (null != ndb.getPic()) {
                        imgurl = ndb.getPic();
                    }
                    Log.e("LiveDetailActivity:","shareurl"+ndb.getNewsurl());
                    ShareDialog dialog = new ShareDialog(activity, R.style.Sharedialog, ndb.getTitle(), ndb.getNewsurl()+"/uid/"+spu.getUser().getUid(), ndb.getPic(), 1);
                    dialog.show();
                }else{
                    PageCtrl.start2LoginActivity(activity);
                }
                break;
            case R.id.ll_newdetail_comments:
                if (spu.getUser() != null) {
                    popCommentActivity(null);
                } else {
                    PageCtrl.start2LoginActivity(activity);
                }
                break;
            case R.id.ll_newdetail_praise:
                praiseContent();
                break;
        }
    }
    //评论弹窗
    private void popCommentActivity(final CommentBean commentBean) {
        if (null == ndb) {
            return;
        }
            ReplyDialog dialog = new ReplyDialog(activity, R.style.ChangeNamedialog, new ReplyDialog.InputListener() {
                @Override
                public void inputstr(String string) {
                    if (commentBean != null) {
                        sendComment(string, commentBean.getCid());
                    } else {
                        sendComment(string, null);
                    }
                }
            });
            dialog.show();
    }
    //发表评论接口
    private void sendComment(String content, String cid) {
        Map<String, String> map = new HashMap<>();
        map.put("lid", bean.getId());
        map.put("uid", spu.getUser().getUid());
        map.put("cid", cid);
        map.put("title", ndb.getTitle());
        map.put("content", content);
        map.put("siteid", InterfaceJsonfile.SITEID);
        Factory.provideHttpService()
                .liveComment(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<ComResultEntity, Boolean>() {
                    @Override
                    public Boolean call(ComResultEntity entity) {
                        LogUtils.i("200-->" + entity.code);
                        if ("200".equals(entity.code)) {
                            LogUtils.i("200-->成功");
                            return true;
                        }
                        LogUtils.i("200失败");
                        return false;

                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<ComResultEntity>() {
                    @Override
                    public void call(ComResultEntity entity) {
                        if ("200".equals(entity.code)) {
                            TUtils.toast("评论成功");
                            commentNumberTx.setText(entity.data.getComcount());
                        } else {
                            TUtils.toast(entity.msg);
                        }
//                            setData();
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        TUtils.toast("评论失败");
                    }
                });
    }
    // 添加收藏
    private void addCollection() {
        Map<String, String> map = new HashMap<>();
        map.put("uid", spu.getUser().getUid());
        map.put("lid", ndb.getId());
        map.put("siteid", InterfaceJsonfile.SITEID);
        Factory.provideHttpService()
                .liveCollection(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<IsCollectionEntity, Boolean>() {
                    @Override
                    public Boolean call(IsCollectionEntity entity) {
                        LogUtils.i("200-->" + entity.code);
                        return "200".equals(entity.code);
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<IsCollectionEntity>() {
                    @Override
                    public void call(IsCollectionEntity entity) {
                        if ("200".equals(entity.code)) {
                            if ("1".equals(entity.data.getStatus())) {
                                TUtils.toast("收藏成功");
                                imgCollection.setImageResource(R.drawable.tabbar_collect_light);
                                collectionNumberTx.setText(entity.data.getFavcount());
                            } else {
                                imgCollection.setImageResource(R.drawable.tabbar_collect);
                                TUtils.toast("收藏取消");
                                collectionNumberTx.setText(entity.data.getFavcount());
                            }
                        } else {
                            TUtils.toast(entity.msg);
                        }
//                        setData();
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                    }
                });
    }
    //赞
    private void praiseContent() {
        Map<String, String> map = new HashMap<>();
        if (spu.getUser() != null) {
            map.put("uid", spu.getUser().getUid());
        }
        map.put("device", DeviceUtils.getMyUUID(activity));
        map.put("lid", ndb.getId());
        map.put("siteid",InterfaceJsonfile.SITEID);
        LogUtils.i("device-->"+DeviceUtils.getMyUUID(activity));
        LogUtils.i("id-->"+bean.getId());
        LogUtils.i("siteid-->"+InterfaceJsonfile.SITEID);
        Factory.provideHttpService().livePraise(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<PraiseNumEntity>() {
                    @Override
                    public void call(PraiseNumEntity baseEntity) {
                        if ("200".equals(baseEntity.code)) {
                            imgPraise.setImageResource(R.drawable.tabbar_like_light);
                            praiseNumberTx.setText(baseEntity.data.getPraisecount());
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {

                    }
                });

    }

    @Override
    public void finish() {
        webview.loadUrl("about:blank");
        super.finish();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    public String getAllDiskCacheDir(){
        String cachePath = "" ;
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)){
            File externalFile=getApplicationContext().getExternalCacheDir();
            if((null!=externalFile)&&(!externalFile.exists()||externalFile.mkdir())){
                cachePath=externalFile.getPath() ;
            }
        }

        if(TextUtils.isEmpty(cachePath)){
            File dir=getApplicationContext().getCacheDir();
            if(!dir.exists()){
                dir.mkdir();
            }
            cachePath=dir.getPath();
        }

        return cachePath;
    }
    private class OnDownloadListener implements DownloadListener {

        @Override
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
            Intent i = new Intent(Intent.ACTION_VIEW);
            i.setData(Uri.parse(url));
            activity.startActivity(i);
        }
    }

    /**
     * 获取视频列表数据
     */
    private void getLiveDetailData(String liveid) {
        Map<String, String> map = new HashMap();
        map.put("siteid", InterfaceJsonfile.SITEID);
        map.put("liveId",liveid);
        if (spu.getUser()!=null){
            map.put("uid", spu.getUser().getUid());
        }
        map.put("device", DeviceUtils.getMyUUID(activity));
        Factory.provideHttpService().livedetail(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<LiveDetailEntity>() {
                    @Override
                    public void call(LiveDetailEntity entity) {
                        setData(entity.data);
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        LogUtils.i("异常-->" + throwable.toString());
                    }
                });
    }



    private void setData(LiveItemBean ndb) {
        this.ndb = ndb;
        try{
            if ("1".equals(ndb.getIspraise())) {
                imgCollection.setImageResource(R.drawable.tabbar_collect_light);
            } else {
                imgCollection.setImageResource(R.drawable.tabbar_collect);
            }
            if ("1".equals(ndb.getIspraise())) {
                imgPraise.setImageResource(R.drawable.tabbar_like_light);
            } else {
                imgPraise.setImageResource(R.drawable.tabbar_like);
            }
            commentNumberTx.setText(ndb.getComcount());
            praiseNumberTx.setText(ndb.getPraisecount());
            collectionNumberTx.setText(ndb.getFavoritecount());
        }catch (Exception e){
            e.printStackTrace();
        }

        webview.loadUrl(ndb.getNewsurl());
    }

}
